import { createRouter } from "./radix3.js";
export class Router {
    addRoute(route) {
        this._router.insert(route.path, route);
        this._routes.push(route);
    }
    find(path) {
        // Remove query params from the path to avoid param issues.
        const hasQuery = path.includes('?');
        const route = this._router.lookup(hasQuery ? path.substring(0, path.indexOf('?')) : path);
        if (!route) {
            return null;
        }
        return {
            handler: route.handler,
            params: route.params,
            path: route.path,
            query: hasQuery ? parseQuery(path) : {}
        };
    }
    removeRoute(path) {
        this._router.remove(path);
        const routeIndex = this._routes.findIndex((route)=>route.path === path);
        this._routes.splice(routeIndex, 1);
    }
    stats() {
        return {
            key: 'radix-router',
            numRoutes: this._routes.length,
            routes: this._routes
        };
    }
    constructor(){
        this._router = createRouter();
        this._routes = [];
    }
}
const parseQuery = (path)=>{
    const query = {};
    // Parse out queries!
    const queries = path.substring(path.indexOf('?') + 1).split('&');
    for (const queryPair of queries){
        const queryPairSplit = queryPair.indexOf('=');
        const key = queryPair.substring(0, queryPairSplit);
        const value = queryPair.substring(queryPairSplit + 1);
        const result = value?.split(',') ?? [];
        const isArray = Array.isArray(result);
        if (isArray) {
            for(let i = 0; i < result.length; i++){
                result[i] = decodeURIComponent(result[i]);
            }
        }
        // Don't store as array if there's only one value
        if (isArray && result.length === 1) {
            query[key] = result[0];
        } else {
            query[key] = result;
        }
    }
    return query;
};
